package com.tanqin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tanqin.constant.MessageConstant;
import com.tanqin.constant.RedisMessageConstant;
import com.tanqin.entity.Result;
import com.tanqin.pojo.Order;
import com.tanqin.service.OrderService;
import com.tanqin.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    @PostMapping("/submit")
    public Result submit(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        // 从 redis 中获取验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        // 比对验证码
        if (validateCode != null && codeInRedis != null && validateCode.equals(codeInRedis)) {
            // 验证通过
            // 设置预约类型，分为微信预约、电话预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            // 预约成功
            if (result.isFlag()) {
                // 给用户发送成功短信
                try {
                    // SMSUtils.ORDER_NOTICE 没有权限操作，暂时换成 SMSUtils.VALIDATE_CODE
                    // 无法发送通用通知，暂时改成发送口令：6666
                    SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, "6666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;

        } else {
            // 验证失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    // 根据预约 id 查询预约详情
    @GetMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
